/**
 * 
 */
package com.effectiv.gooruda.startup;

import java.util.Date;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.effectiv.gooruda.domain.ServerDetail;
import com.effectiv.gooruda.repository.ServerDetailRepository;


/**
 * @author Dhrubo
 * 
 */
@Component
@Slf4j
public class ApplicationStartupProcessor implements
		ApplicationListener<ContextRefreshedEvent> {
	
	@Value("#{settings['server']}")
	private String name;
	@Value("#{settings['port']}")
	private int port;
	@Value("#{settings['context']}")
	private String context;
	
	@Autowired
	private ServerDetailRepository repository;

	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		log.info("##### Registering API server - {}, {}, {}", name, port, context);
		
		ServerDetail server = repository.findByNameAndPortAndContext(name, port, context);
		
		log.info("Server detail - {}", server);
		
		if(server == null){
			server = new ServerDetail();
			server.setContext(context);
			server.setName(name);
			server.setPort(port);
			server.setStart(new Date());
		}
		else{
			server.setStart(new Date());
		}
		
		repository.save(server);
	}

}
